package cn.itcast.hotel.service.impl;

import cn.itcast.hotel.mapper.HotelMapper;
import cn.itcast.hotel.pojo.Hotel;
import cn.itcast.hotel.pojo.HotelDoc;
import cn.itcast.hotel.pojo.PageResult;
import cn.itcast.hotel.pojo.RequestParams;
import cn.itcast.hotel.service.IHotelService;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.geo.GeoPoint;
import org.elasticsearch.common.unit.DistanceUnit;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.elasticsearch.search.suggest.Suggest;
import org.elasticsearch.search.suggest.SuggestBuilder;
import org.elasticsearch.search.suggest.SuggestBuilders;
import org.elasticsearch.search.suggest.completion.CompletionSuggestion;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class HotelService extends ServiceImpl<HotelMapper, Hotel> implements IHotelService {
@Autowired
  private RestHighLevelClient client;
  @Override
  public PageResult search(RequestParams params)  {
    try {
      //1.准备request对象
      SearchRequest request = new SearchRequest("hotel");
      //2.1封装(条件的构造有点复杂，所以进行条件封装)
      buildBasicQuery(params,request);
      //2.2分页
      int page = params.getPage();
      int size = params.getSize();
      request.source().from((page - 1) * size).size(size);

      //2.3排序 获得当前位置
      String location = params.getLocation();
      if (location != null && !location.equals("")) {
        request.source().sort(SortBuilders
          .geoDistanceSort("location", new GeoPoint(location))
          .order(SortOrder.ASC)
          .unit(DistanceUnit.KILOMETERS)
        );
      }

      // 3.发送请求
      SearchResponse response = client.search(request, RequestOptions.DEFAULT);
      // 4.解析响应
      return handleResponse(response);
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
  }

  /**
   * 搜索联想
   * @param prefix
   * @return
   */
  @Override
  public List<String> getSuggestions(String prefix) {
    try {
      //1.准备对象
      SearchRequest request = new SearchRequest("hotel");
      //2.addSuggestion添加一个补全查询
      request.source().suggest(new SuggestBuilder().addSuggestion(
        //name：自动补全的名字叫什么，可以随便起completionSuggestion用的completion联想自动补全的功能，suggestion根据这个字段联想
        "suggestions",SuggestBuilders.completionSuggestion("suggestion")
          //用户搜索需要联想的词组
          .prefix(prefix)
          //去除重复
          .skipDuplicates(true)
          //默认只展示10条
          .size(10)
      ));
      //3.向es客户端发送DsL语句
      SearchResponse response = client.search(request, RequestOptions.DEFAULT);
      //System.out.println(response);
      //4.1解析结果,获取suggest下的联想数据
      Suggest suggest = response.getSuggest();
      CompletionSuggestion suggestions = suggest.getSuggestion("suggestions");
      //Suggest.Suggestion<? extends Suggest.Suggestion.Entry<? extends Suggest.Suggestion.Entry.Option>> = CompletionSuggestion
      List<CompletionSuggestion.Entry.Option> options = suggestions.getOptions();
      //4.3为什么用size，就是知道长度，先扩容，如果在添加时扩容，内存会消耗很大
      List<String> list =new ArrayList<>(options.size());
      //4.2遍历options
      for (CompletionSuggestion.Entry.Option option : options) {
        String text = option.getText().toString();
        //4.4不能打印，所以我们可以创建数组System.out.println(text);
        list.add(text);
      }
      return list;
    } catch (IOException e) {
      //ctrl+alt+t 快捷键可以用来try/catch
      throw new  RuntimeException(e);
    }
  }

  /**
   * 聚合查询
   * @param params
   * @return
   */
  @Override
  public Map<String, List<String>> filters(RequestParams params) {
    try {
      // 1.准备Request
      SearchRequest request = new SearchRequest("hotel");
      // 2.准备DSL
      // 2.1.query
      buildBasicQuery(params, request);
      // 2.2.设置size
      request.source().size(0);
      // 2.3.聚合
      buildAggregation(request);
      // 3.发出请求
      SearchResponse response = client.search(request, RequestOptions.DEFAULT);
      // 4.解析结果
      Map<String, List<String>> result = new HashMap<>();
      Aggregations aggregations = response.getAggregations();
      // 4.1.根据品牌名称，获取品牌结果
      List<String> brandList = getAggByName(aggregations, "brandAgg");
      result.put("brand", brandList);
      // 4.2.根据品牌名称，获取品牌结果
      List<String> cityList = getAggByName(aggregations, "cityAgg");
      result.put("city", cityList);
      // 4.3.根据品牌名称，获取品牌结果
      List<String> starList = getAggByName(aggregations, "starAgg");
      result.put("starName", starList);

      return result;
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
  }

  private void buildAggregation(SearchRequest request) {
    request.source().aggregation(AggregationBuilders
      .terms("brandAgg")
      .field("brand")
      .size(100)
    );
    request.source().aggregation(AggregationBuilders
      .terms("cityAgg")
      .field("city")
      .size(100)
    );
    request.source().aggregation(AggregationBuilders
      .terms("starAgg")
      .field("starName")
      .size(100)
    );
  }

  private List<String> getAggByName(Aggregations aggregations, String aggName) {
    // 4.1.根据聚合名称获取聚合结果
    Terms brandTerms = aggregations.get(aggName);
    // 4.2.获取buckets
    List<? extends Terms.Bucket> buckets = brandTerms.getBuckets();
    // 4.3.遍历
    List<String> brandList = new ArrayList<>();
    for (Terms.Bucket bucket : buckets) {
      // 4.4.获取key
      String key = bucket.getKeyAsString();
      brandList.add(key);
    }
    return brandList;
  }





  // 结果解析
  private PageResult handleResponse(SearchResponse response) {
    // 4.解析响应
    SearchHits searchHits = response.getHits();
    // 4.1.获取总条数
    long total = searchHits.getTotalHits().value;
    // 4.2.文档数组
    SearchHit[] hits = searchHits.getHits();
    // 4.3.遍历
    List<HotelDoc> hotels = new ArrayList<>();
    for (SearchHit hit : hits) {
      // 获取文档source
      String json = hit.getSourceAsString();
      // 反序列化
      HotelDoc hotelDoc = JSON.parseObject(json, HotelDoc.class);
      //
      Object[] sortValues = hit.getSortValues();
      if (sortValues.length>0){
        Object sortValue=sortValues[0];
        hotelDoc.setDistance(sortValue);
      }

      // 放入集合
      hotels.add(hotelDoc);
    }
    // 4.4.封装返回
    return new PageResult(total, hotels);
  }

  /**
   * 组合查询必须要用bool
   * @param params
   * @param request
   */
  private void buildBasicQuery(RequestParams params, SearchRequest request) {
    // 1.构建BooleanQuery
    BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
    // 2.关键字搜索,判断为空则直接查询所有，不为空查询all中的字段
    String key = params.getKey();
    if (key == null || "".equals(key)) {
      boolQuery.must(QueryBuilders.matchAllQuery());
    } else {
      boolQuery.must(QueryBuilders.matchQuery("all", key));
    }
    // 3.城市条件
    if (params.getCity() != null && !params.getCity().equals("")) {
      boolQuery.filter(QueryBuilders.termQuery("city", params.getCity()));
    }
    // 4.品牌条件
    if (params.getBrand() != null && !params.getBrand().equals("")) {
      boolQuery.filter(QueryBuilders.termQuery("brand", params.getBrand()));
    }
    // 5.星级条件
    if (params.getStarName() != null && !params.getStarName().equals("")) {
      boolQuery.filter(QueryBuilders.termQuery("starName", params.getStarName()));
    }
    // 6.价格
    if (params.getMinPrice() != null && params.getMaxPrice() != null) {
      boolQuery.filter(QueryBuilders
        .rangeQuery("price")
        .gte(params.getMinPrice())
        .lte(params.getMaxPrice())
        //>=get <=lte
      );
    }

    // 2.算分控制
    FunctionScoreQueryBuilder functionScoreQuery =
      QueryBuilders.functionScoreQuery(
        // 原始查询，相关性算分的查询
        boolQuery,
        // function score的数组
        new FunctionScoreQueryBuilder.FilterFunctionBuilder[]{
          // 其中的一个function score 元素
          new FunctionScoreQueryBuilder.FilterFunctionBuilder(
            // 过滤条件
            QueryBuilders.termQuery("isAD", true),
            // 算分函数乘十
            ScoreFunctionBuilders.weightFactorFunction(10)
          )
        });
    request.source().query(functionScoreQuery);
    // 7.放入source
  }


  @Override
  public void deleteById(Long id) {
    try {
      // 1.准备Request
      DeleteRequest request = new DeleteRequest("hotel", id.toString());
      // 2.发送请求
      client.delete(request, RequestOptions.DEFAULT);
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
  }

  @Override
  public void insertById(Long id) {
    try {
      // 0.根据id查询酒店数据
      Hotel hotel = getById(id);
      // 转换为文档类型
      HotelDoc hotelDoc = new HotelDoc(hotel);

      // 1.准备Request对象
      IndexRequest request = new IndexRequest("hotel").id(hotel.getId().toString());
      // 2.准备Json文档
      request.source(JSON.toJSONString(hotelDoc), XContentType.JSON);
      // 3.发送请求
      client.index(request, RequestOptions.DEFAULT);
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
  }

}
